package edu.neusoft.yiqibike.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import edu.neusoft.yiqibike.common.datasource.TargetDataSource;
import edu.neusoft.yiqibike.common.entity.mysql.AccountLog;
import edu.neusoft.yiqibike.common.entity.mysql.AccountRecord;
import edu.neusoft.yiqibike.common.entity.vo.AccountVo;
import edu.neusoft.yiqibike.dao.mapper.AccountLogMapper;
import edu.neusoft.yiqibike.service.IAccountService;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.OffsetDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * User：lyc
 * Date：2017-12-24
 * Time：21:07
 * Description：
 */
@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    @TargetDataSource(name = "ds2")
    public AccountVo getAccountInfo(Page<AccountLog> page) {
        if (Objects.nonNull(page) && !CollectionUtils.isEmpty(page.getCondition())) {
            Long uid = Long.valueOf((String) page.getCondition().get("uid"));
            if (Objects.nonNull(uid)) {
                Wrapper wrapper = new EntityWrapper().eq("uid", uid);
                AccountRecord accountRecord = new AccountRecord().selectOne(wrapper);
                List<AccountLog> accountLogs = accountLogMapper.selectByPage(page, uid);
                accountLogs = accountLogs.stream().sorted(Comparator.comparing(AccountLog::getCreateTime)).collect(Collectors.toList());
                page.setRecords(accountLogs);
                AccountVo accountVo = new AccountVo();
                accountVo.setRecord(accountRecord);
                accountVo.setLog(page);
                return accountVo;
            }
        }
        return null;
    }
}
